package com.mjgy.service.impl;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.common.utils.R;
import com.mjgy.entity.NoticeEntity;
import com.mjgy.service.NoticeService;

/**
* @Description: TODO
* @author LGC
* @date 2018年10月2日
* @version V1.0
*/
@Service
@Transactional
public class NoticeServiceImpl implements NoticeService {

	@Autowired
	private EntityManager em;
	
	@Override
	public R saveNotice(String title, String content) {
		NoticeEntity ne = new NoticeEntity();
		ne.setTitle(title);
		ne.setContent(content);
		ne.setCreateTime(new Date());
		em.persist(ne);
		return R.success();
	}

	@Override
	public R updateNotice(Long noticeId, String title, String content) {
		NoticeEntity ne = em.find(NoticeEntity.class, noticeId);
		if(ne == null) {
			return R.error(202, "没有客服消息");
		}
		
		ne.setTitle(title);
		ne.setContent(content);
		ne.setUpdateTime(new Date());
		em.merge(ne);
		return R.success();
	}

	@Override
	public R getNotice() {
		StringBuilder sql = new StringBuilder();
		sql.append("from NoticeEntity");
		Query query = em.createQuery(sql.toString());
		List<NoticeEntity> list = query.getResultList();
		for(NoticeEntity ne : list) {
			return R.success().put("data", ne);
		}
		
		return R.error(202, "没有客服消息");
	}

}
